10 April 2019

Prerequisites

Packages

library(htmlwidgets) #install.packages("htmlwidgets")
library(dygraphs) #install.packages("dygraphs") 
library(flexdashboard) # install.packages("flexdashboard")
library(DT) #install.packages("DT")
library(shiny) #install.packages("shiny")
library(plotly) #install.packages("plotly")
library(ggplot2) 

Interactive dashboards

Why use dashboards?

  • R, it provides three core plotting systems:

    • base plots
    • lattice plots
    • ggplot2 plots
  • writing codes for plotting graphs in R time & again can get tiring
  • difficult to create an interactive visualization for story narration using above packages

Goal of a dashboard

  • Translate complicated data into a more readable, more understandable format for less technical people

  • Dashboards allow non-data scientists to see the numbers that are important to them upfront and make connections based on their expertise

  • Share your analysis (in an interactive manner) with the community

htmlwidgets

A framework for creating HTML widgets that render in various contexts including the R console, 'R Markdown' documents, and 'Shiny' web applications.

htmlwidgets seamlessly bridges R and JavaScript. HTML widgets work just like R plots except they produce interactive web visualizations.

There are over 30 packages on CRAN which provide htmlwidgets: Available widgets

htmlwidgets example

dygraph(nhtemp, main = "New Haven Temperatures") %>% 
  dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01"))

Time-series data visualization

flexdashboard

flexdashboard

Purpose: To create interactive dashboards using rmarkdown.

  • Use R Markdown to publish a group of related data visualizations as a dashboard.

  • Ideal for publishing interactive JavaScript visualizations based on htmlwidgets (also works with standard base, lattice, and grid graphics).

  • Flexible and easy to specify row and column-based layouts. Charts are intelligently re-sized to fill the browser and adapted for display on mobile devices.

  • Storyboard layouts for presenting sequences of visualizations and related commentary.

flexdashboard example

Creating a flexdashboard

You can create a flexdashboard in R Markdown document with the flexdashboard::flex_dashboard output format.

Basic layout

Dashboards are divided into columns and rows. Output components are delineated using level 3 markdown headers (###).

By default, dashboards are laid out within a single column, with charts stacked vertically within a column and sized to fill available browser height.

Example layout: Single column with two charts:

Multiple columns

To lay out charts using multiple columns you introduce a level 2 markdown header (--------------) for each column. For example, this dashboard displays 3 charts split across two columns. Chart 1 is moved into its own columny, which has also been given a larger size via the data-width attribute:

Layout by row

You can orient dashboards row-wise by specifying the orientation: rows option:

Scrolling layout

Flexdashboard charts are laid out to automatically fill the height of the browser. If you have many charts you’ll probably want to scroll rather than fit them all onto the page. You can control this behavior using the vertical_layout option and specify scroll to layout charts at their natural height, scrolling the page if necessary.

Tabsets

You can also lay components out as a tabset.

To layout a row or column as a tabset you simply add the {.tabset} attribute to the section heading:

Including Components

You include htmlwidgets in an R Markdown document just like you include R plots:

Note: htmlwidgets embed data directly in their host web page which could lead to performance problems for larger datasets. For larger dataset sizes the use of standard R graphics may be preferable.

R Graphics

You can use any chart created with standard R graphics (base, lattice, ggplot2, etc.) with flexdashboard.

When creating static (non-Shiny) dashboards containing standard R graphics it’s critical to define knitr fig.width and fig.height values as close as possible to what they’ll actually be on the page

Static tables

A simple table is ideal for smaller numbers of records (i.e. 40-50 or less). For static dashboards, you can use the knitr::kable function to output your dataset:

knitr::kable(mtcars)
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 0 3 1
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 0 4 2
Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 0 4 4
Merc 280C 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3
Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Toyota Corona 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1
Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2
Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4
Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
Ferrari Dino 19.7 6 145.0 175 3.62 2.770 15.50 0 1 5 6
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
Volvo 142E 21.4 4 121.0 109 4.11 2.780 18.60 1 1 4 2

Dynamic data tables

The DT package (an interface to the DataTables JavaScript library) can display R matrices or data frames as interactive HTML tables that support filtering, pagination, and sorting.

DT::datatable(mtcars, options = list(bPaginate = FALSE))

Value Boxes

You can use the valueBox function to display single values along with a title and optional icon:

More layout options

Plotly

Plotly

  • Allows to easily translate ggplot2 graphics to an interactive web-based version.

  • The R package also provides high-level bindings for working directly with the plotly.js graphing library.

  • Plotly Cheatsheet

ggplotly

p <- ggplot(data = diamonds, aes(x = cut, fill = clarity)) +
            geom_bar(position = "dodge")
ggplotly(p)

Choropleth map with plot_ly

plot_ly(
type = 'choropleth',
locations = c('AZ','CA','VT'),
locationmode = 'USA-states',
colorscale = 'Viridis' ,
z = c(10 ,20 ,40 )) %>% 
layout(geo = list(scope = 'usa'))

Choropleth Maps

Shiny

Shiny

Shiny is an R package that makes it easy to build interactive web apps straight from R. You can host standalone apps on a webpage or embed them in R Markdown documents or build dashboards.

Shiny Example: Movie Explorer

Structure of a Shiny App

Shiny apps are contained in a single script called app.R. The script app.R lives in a directory (for example, newdir/) and the app can be run with runApp("newdir").

  • app.R has three components:

    • a user interface object
    • a server function
    • a call to the shinyApp function

The user interface (ui) object controls the layout and appearance of your app. The server function contains the instructions that your computer needs to build your app. Finally the shinyApp function creates Shiny app objects from an explicit UI/server pair.

Shiny is a single-file app, which means you can copy and paste the entire app into the R console.

Hello Shiny UI Layout

# Define UI for app that draws a histogram ----
ui <- fluidPage(
  titlePanel("Hello Shiny!"), # App title
  sidebarLayout(  # Sidebar layout with input and output definitions
    sidebarPanel( # Sidebar panel for inputs
      sliderInput(inputId = "bins", # Input: Slider for the number of bins
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)),
    mainPanel( # Main panel for displaying outputs
      plotOutput(outputId = "distPlot") # Output: Histogram
    )
  )
)

Hello Shiny server

# Define server logic required to draw a histogram ----
server <- function(input, output) {
  # Histogram of the Old Faithful Geyser Data ----
  output$distPlot <- renderPlot({
    
    x    <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)
    
    hist(x, breaks = bins, col = "#75AADB", border = "white",
         xlab = "Waiting time to next eruption (in mins)",
         main = "Histogram of waiting times")
    })
}

Complete structure of a Shiny app

ui <- ...

server <- ...

shinyApp(ui = ui, server = server)

Running an app

Every Shiny app has the same structure: an app.R file that contains ui and server. You can create a Shiny app by making a new directory and saving an app.R file inside it. It is recommended that each app will live in its own unique directory.

You can run a Shiny app by giving the name of its directory to the function runApp. For example if your Shiny app is in a directory called my_app, run it with the following code:

runApp("my_app") # assumes the app directory is wd

Exercise

Create a new directory named App-1 in your working directory. Then copy and paste the app.R script from Hello Shiny.

Launch your app by running runApp("App-1"). Then click escape and make some changes to your app:

  • Change the title from "Hello Shiny!" to "Hello World!".

  • Set the minimum value of the slider bar to 5.

  • Change the histogram border color from "white" to "orange".

Exercise

When you are ready, launch your app again. Your new app should match the image below.

More Shiny examples

You can create Shiny apps by copying and modifying existing Shiny apps. The Shiny gallery provides some good examples, or use the eleven pre-built Shiny examples listed below.

runExample("01_hello")      # a histogram
runExample("02_text")       # tables and data frames
runExample("03_reactivity") # a reactive expression
runExample("04_mpg")        # global variables
runExample("05_sliders")    # slider bars
runExample("06_tabsets")    # tabbed panels
runExample("07_widgets")    # help text and submit buttons
runExample("08_html")       # Shiny app built from HTML
runExample("09_upload")     # file upload wizard
runExample("10_download")   # file download wizard
runExample("11_timer")      # an automated timer

Shiny with flexdashboard

You can easily add Shiny to a flexdashboard and enable viewers to change underlying parameters and see the results immediately. This is done by adding runtime: shiny to a standard flexdashboard and then adding one or more input controls that dynamically drive the appearance of the components within the dashboard.

Using Shiny with flexdashboard turns a static R Markdown visualization into an interactive tool. Note: interactive dashboards need to be deployed to a Shiny Server to be shared broadly.

You can also use the shinydashboard package to create a shiny dashboard.

Creating a shiny flexdashboard

The steps required to add Shiny components to a flexdashboard are as follows:

  1. Add runtime: shiny to the options declared at the top of the document (YAML front matter).

  2. Add the {.sidebar} attribute to the first column of the dashboard to make it a host for Shiny input controls.

  3. Add Shiny inputs and outputs as appropriate.

  4. When including plots, be sure to wrap them in a call to renderPlot to ensure that graphs dynamically respond to changes and are automatically re-sized.

Shiny flexdashboard example

Another Shiny flexdashboard examples

Homework Exercises

Homework Exercises

Create a dashboard for the flights data in the nycflights13 package. For example, your dashboard could show a linegraph of the total flights per month or the average delay per month. You could also embed a shiny app that let's you select an airline carrier or a specific destination.

You can use this dashboard for inspiration. The code to create the dashboard app is located here

Deadline: Tuesday, April 16.